package com.mvd.app.ac2019;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.mvd.app.R;
import com.mvd.app.ac2021.ErrorMsgActivity;
import com.mvd.app.activity.BaseActivity;

import com.mvd.app.activity.SettingActivity;
import com.mvd.app.application.BaseApplication;
import com.mvd.app.commons.CommonUtils;
import com.mvd.app.commons.PDALogUtils;
import com.mvd.app.commons.UtilsLog;
import com.mvd.app.model.CarsInforModel;
import com.mvd.app.model.VideoUploadModel;
import com.mvd.app.upload.MyUploadService;
import com.mvd.app.upload.Util;
import com.vincent.videocompressor.VideoCompress;
import com.werb.permissionschecker.PermissionChecker;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 新版进入后的第一个页面
 * 导航页
 * 四个大按钮
 **/
public class FirstActivity extends BaseActivity {

    @BindView(R.id.first_imageView)
    ImageView imageView;
    @BindView(R.id.textView)
    TextView textView;
    @BindView(R.id.ac_first_waijian)
    TextView acFirstWaijian;
    @BindView(R.id.ac_login_view_m)
    TextView acLoginViewM;
    @BindView(R.id.ac_first_dipandongtai)
    TextView acFirstDipandongtai;
    @BindView(R.id.ac_first_lushi)
    TextView acFirstLushi;
    @BindView(R.id.ac_login_view_m123)
    TextView acLoginViewM123;
    @BindView(R.id.ac_first_setting)
    TextView acFirstSetting;

    private FirstActivity instance;
    public static String[] permissionArray = new String[]{
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_SETTINGS,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.CAMERA,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.READ_CALENDAR,
            Manifest.permission.RECORD_AUDIO,
    };

    private PermissionChecker permissionChecker;
    List<VideoUploadModel> VideoUploadModelList = new ArrayList<>();
    private long startTime, endTime;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);
        ButterKnife.bind(this);
        instance = this;
        permissionChecker = new PermissionChecker(this); // initialize，must need

        if (permissionChecker.isLackPermissions(permissionArray)) {
            permissionChecker.requestPermissions();
            UtilsLog.e("请求录像权限失败===");
        } else {
            // startVideo();
            UtilsLog.e("请求录像权限成功===");
        }
        bindService();

        getDB();
    }

    @OnClick({R.id.ac_first_waijian, R.id.ac_first_dipandongtai,
            R.id.ac_first_lushi, R.id.ac_first_setting,
            R.id.first_imageView})
    public void onViewClicked(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.ac_first_waijian:
                intent = new Intent(instance, LoginActivity.class);
                BaseApplication.JIANCE_MODE = 0;
                break;
            case R.id.ac_first_dipandongtai:
                intent = new Intent(instance, LoginActivity.class);
                BaseApplication.JIANCE_MODE = 2;
                break;
            case R.id.ac_first_lushi:
                intent = new Intent(instance, LoginActivity.class);
                BaseApplication.JIANCE_MODE = 1;
                break;
            case R.id.ac_first_setting:
                intent = new Intent(instance, SettingActivity.class);
                break;
            case R.id.first_imageView:
//                intent=new Intent(instance, ErrorMsgActivity.class);
//                intent.putExtra("error_msg", CommonUtils.readAssetsTxt(instance,"error"));
                break;
//            Intent i=new Intent(instances, ErrorMsgActivity.class);
//            i.putExtra("error_msg", CommonUtils.readAssetsTxt(instances,"error.txt"));
//            startActivity(i);
        }
        if (intent != null) {
            startActivity(intent);
        }
    }

    private long exitTime = 0;

    // 双击返回退出程序
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序",
                        Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                BaseApplication.getSelf().exit(this);
                this.finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        String logStrf = "\n" + "onDestroy-----FirstActivity-------" + "\n";
        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStrf.getBytes());
        unBindService();
    }

    /**
     * Get db.
     * 查询数据库
     * 获取没有上传完成的视频
     */
    void getDB() {
        VideoUploadModelList = VideoUploadModel.find(VideoUploadModel.class, "statement=?", "0");
        if (VideoUploadModelList != null && VideoUploadModelList.size() > 0) {
            for (int i = 0; i < VideoUploadModelList.size(); i++) {
                UtilsLog.e("VideoUploadModelList==" + i + "===" + VideoUploadModelList.get(i));
                String logStr22 = "\n" + "getDB()---录像路径---" + "\n" + "DB--data==" + "\n" +
                        VideoUploadModelList.toString() + "\n";
                PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr22.getBytes());
                VideoUploadModel model = VideoUploadModelList.get(i);
                videoCompress2(model.getSize(), model.getZp(), model);
            }
        }
        List<VideoUploadModel> VideoUploadModelList2 = new ArrayList<>();
        VideoUploadModelList2 = VideoUploadModel.find(VideoUploadModel.class, "statement=?", "0");
        if (VideoUploadModelList2 != null && VideoUploadModelList2.size() > 0) {
            for (int i = 0; i < VideoUploadModelList2.size(); i++) {
                long id = VideoUploadModelList2.get(i).getId();
                VideoUploadModel user = VideoUploadModel.findById(VideoUploadModel.class, id);
                user.delete();
            }
        }
    }

    //    void videoCompress(String videoUriString, String videoPath, final VideoUploadModel model) {
//        VideoSlimmer.convertVideo(videoUriString, videoPath, 480, 800, 200 * 360 * 30, new VideoSlimmer.ProgressListener() {
//            @Override
//            public void onStart() {
//            }
//
//            @Override
//            public void onFinish(boolean result) {
//                UtilsLog.e("videoCompress---视频路径=onFinish=" + result);
////                //convert finish,result(true is success,false is fail)
//                getDataUploadVideo(model);
//            }
//
//            @Override
//            public void onProgress(float percent) {
//                UtilsLog.e("videoCompress---视频路径=onProgress=" + percent);
//            }
//        });
//    }
    void videoCompress2(String videoUriString, String videoPath, final VideoUploadModel model) {
//        String destPath = tv_output.getText().toString() + File.separator + "VID_" + new SimpleDateFormat("yyyyMMdd_HHmmss", getLocale()).format(new Date()) + ".mp4";
        VideoCompress.compressVideoMedium(videoUriString, videoPath, new VideoCompress.CompressListener() {
            @Override
            public void onStart() {
                String str = "Compressing..." + "\n"
                        + "Start at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date());
                UtilsLog.e("onStart==" + str);
                startTime = System.currentTimeMillis();
                Util.writeFile(BaseApplication.getSelf(), "Start at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()) + "\n");
            }

            @Override
            public void onSuccess() {
                String str = "\n"
                        + "Compress Success!" + "\n"
                        + "End at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date());
                UtilsLog.e("onSuccess==" + str);
                endTime = System.currentTimeMillis();
                Util.writeFile(BaseApplication.getSelf(), "End at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()) + "\n");
                Util.writeFile(BaseApplication.getSelf(), "Total: " + ((endTime - startTime) / 1000) + "s" + "\n");
                Util.writeFile(BaseApplication.getSelf());
                getDataUploadVideo(model);
            }

            @Override
            public void onFail() {
                UtilsLog.e("onFail==Compress Failed!" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()));
                endTime = System.currentTimeMillis();
                Util.writeFile(BaseApplication.getSelf(), "Failed Compress!!!" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()));
            }

            @Override
            public void onProgress(float percent) {
                String str = String.valueOf(percent) + "%";
                UtilsLog.e("onProgress====" + str);
            }
        });
    }

    private Locale getLocale() {
        Configuration config = getResources().getConfiguration();
        Locale sysLocale = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            sysLocale = getSystemLocale(config);
        } else {
            sysLocale = getSystemLocaleLegacy(config);
        }

        return sysLocale;
    }

    @SuppressWarnings("deprecation")
    public static Locale getSystemLocaleLegacy(Configuration config) {
        return config.locale;
    }

    @TargetApi(Build.VERSION_CODES.N)
    public static Locale getSystemLocale(Configuration config) {
        return config.getLocales().get(0);
    }

    //上传视频
    private void getDataUploadVideo(final VideoUploadModel carsInforModel) {
        UtilsLog.e("MyUploadService---上传视频---url==" + carsInforModel.getPath());
        OkGo.<String>post(carsInforModel.getPath())
                //次数
                .params("Times", carsInforModel.getTimes())
                //PlatformSN
                .params("PlatformSN", carsInforModel.getPlatformSN())
                .params("VideoType", carsInforModel.getVideoType())
                .params("ItemCode", carsInforModel.getItemCode())
                //车牌号码，两个拼起来的
                .params("CarNO", carsInforModel.getCarNO())
                //号牌类型
                .params("PlateType", carsInforModel.getPlateType())
                //外检车道，检测线代号
                .params("Line", carsInforModel.getLine())
                //车辆识别代码
                .params("VIN", carsInforModel.getVIN())
                //照片
                .params("zp", new File(carsInforModel.getZp()))
                //开始时间
                .params("StartTime", carsInforModel.getStartTime())
                //结束时间
                .params("EndTime", carsInforModel.getEndTime())
                .execute(new StringCallback() {
                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
//                        CommonUtils.showLoadingDialog(instances, "上传中...");
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
//                        CommonUtils.hideLoadingDialog(instances);
                        String result = response.body();
                        UtilsLog.e("MyUploadService---上传视频-result==" + result);
                        String logStr = "\n" + "MyUploadService---外检上传视频--请求成功" +
                                "\n" + "URL::" + carsInforModel.getPath() + "\n" + "result:" + response.body() + "\n";
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
                        if (!TextUtils.isEmpty(result) && !"[[]]".equals(result) && !"[{}]".equals(result)
                                && !"[]".equals(result)) {
                            String newResult = result.substring(1, result.length() - 1).replaceAll("\\\\",
                                    "");
                            UtilsLog.e("MyUploadService---上传视频-newResult==" + newResult);
                            if ("ok".equalsIgnoreCase(newResult)) {
                                UtilsLog.e("MyUploadService---上传视频-成功==");
                                carsInforModel.setStatement("1");
                                carsInforModel.save();
                            }
                        } else {
                            UtilsLog.e("MyUploadService---上传视频-result==" + "没有数据");
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
//                        UpVideo_ok = false;
                        UtilsLog.e("MyUploadService---上传视频-onError==" + response.body());
                        UtilsLog.e("MyUploadService---上传视频-onError==" + response.getException());
                        String logStr = "\n" + "MyUploadService---上传录像视频-onError-失败" +
                                "\n" + "URL::" + carsInforModel.getPath() + "\n" + "result:" + response.body() + "\n" +
                                response.getException() + "\n" + response.message() + "\n";
                        PDALogUtils.createLogFile(BaseApplication.JIANCE_MODE, logStr.getBytes());
//                        CommonUtils.hideLoadingDialog(instances);
//                        Toast.makeText(instances, "上传录像失败，请重试", Toast.LENGTH_LONG).show();
                    }
                });
    }

    //开启服务
    public void startService(String str) {
        //开启服务需要Intent对象,和Activity跳转类似
        Intent intent = new Intent(this, MyUploadService.class);
        intent.putExtra("service_data", str);
        startService(intent);

    }

    //开启服务
    public void startService(CarsInforModel model) {
        //开启服务需要Intent对象,和Activity跳转类似
        Intent intent = new Intent(this, MyUploadService.class);
        intent.putExtra("service_model", model);
        startService(intent);

    }

    //停止服务
    public void stopService() {
        //停止服务的方法
        stopService(new Intent(this, MyUploadService.class));
    }

    //绑定服务
    public void bindService() {
        //绑定服务
        bindService(new Intent(this, MyUploadService.class), conn, flags);
    }

    //解绑服务
    public void unBindService() {
        //防止在没有绑定的情况下，去解除绑定，抛出异常
        try {
            //解除绑定
            unbindService(conn);
        } catch (Exception e) {
            System.out.println("MainActivity.unBindService" + e);
        }
    }

    //服务绑定的连接对象
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };

    //服务绑定的标识
    //BIND_AUTO_CREATE 绑定的同时，启动Service
    private int flags = Service.BIND_AUTO_CREATE;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case PermissionChecker.PERMISSION_REQUEST_CODE:
                if (permissionChecker.hasAllPermissionsGranted(grantResults)) {
                    // 执行你的相关操作
//                    if(type == 1){
//                        startAudio();
//                    }else if(type == 2){
//                        startVideo();
//                    }
                } else {
                    // 权限拒绝后的提示
                    permissionChecker.showDialog();
                }
                break;
        }
    }
}
